package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.Category;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.Random;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //password加密
        String psw = DigestUtils.md5DigestAsHex(password.getBytes());
        // TODO 后期需要进行md5加密，然后再进行比对
        if (!psw.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     * @param dto
     * @return
     */
    @Override
    public Result<Object> add(EmployeeDTO dto) {
        /**
         * 判断非空
         */
        //1.参数校验，非空判断,提升代码的健壮性
        if(dto.getUsername()==null){
            return Result.error(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //2.根据账号去查询数据库是否存在，如果存在，则直接返回错误信息
        Employee employee = employeeMapper.getByUsername(dto.getUsername());
        if(employee!=null){
            return Result.error(MessageConstant.PASSWORD_EXEIT_ERROR);
        }


        employee=new Employee();
        //默认密码
        BeanUtils.copyProperties(dto,employee);
        //默认状态开启
        employee.setStatus(StatusConstant.ENABLE);
        //加密密码
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

        //修改时间和创建时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        //设置人和修改人
        employee.setCreateUser(10L);
        employee.setUpdateUser(10L);

        employeeMapper.insert(employee);
        return Result.success();
    }


    /**
     * 分页查询
     * @param dto
     * @return
     */
    @Override
    public Result page(EmployeePageQueryDTO dto) {

        //非空判断
        if (dto.getPage() ==null){
            dto.setPage(1);
        }
        if (dto.getPageSize()==null){
            dto.setPageSize(5);
        }
        //开启分页
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        //调用mapper接口
        Page<Employee> pageParam = employeeMapper.pageQuery(dto);

        //封装返回数据
        PageResult pageResult=new PageResult();
        pageResult.setTotal(pageParam.getTotal());
        pageResult.setRecords(pageParam.getResult());

        return Result.success(pageResult);
    }


    /**
     * 禁用员工账号
     * @param status
     * @param id
     * @return
     */
    @Override
    public Result updateEmpStatus(Integer status, Long id) {

        //非空判断
        if (id==null){
        return Result.error(MessageConstant.ID_NOT_FOUND);

        }
        if (status==null){
            return  Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //调用mapper接口
        Employee employee=new Employee();
        employee.setId(id);
        employee.setStatus(status);
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.updateEmp(employee);
        //返回数据
        return null;
    }

    /**
     * 查询员工
     * @param id
     * @return
     */
    @Override
    public Result<Employee> getEmpById(Long id) {

        //判断非空
        if (id==null){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        //调用mapper

        Employee employee = employeeMapper.getById(id);
        employee.setPassword("*******");
        //返回数据
        return Result.success(employee);
    }

    /**
     * 编辑员工
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public Result updateEmp(EmployeeDTO dto) {

        //判断非空
        if (dto.getId()==null){

            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        //调用mapper接口
        Employee employee=new Employee();
        //复制实体类
        BeanUtils.copyProperties(dto,employee);

        employee.setUpdateTime(LocalDateTime.now());
        //修改人
        employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.updateEmp(employee);
        //返回数据
        return Result.success();
    }




}
